﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Microsoft.Practices.ObjectBuilder;
using Kent.Boogaart.HelperTrinity;
using WPFCABShell.Shell.Interface.Services.Options;

namespace WPFCABShell.Shell.Options.Plugins
{
	/// <summary>
	/// Interaction logic for PluginManagerView.xaml
	/// </summary>
	public partial class PluginsView : IPluginsView, IOptionsPane
	{
		public static readonly DependencyProperty PresenterProperty = DependencyProperty.Register("Presenter",
			typeof(PluginsPresenter),
			typeof(PluginsView),
			new FrameworkPropertyMetadata(Presenter_Changed));

		public static readonly DependencyProperty PluginInfosProperty = DependencyProperty.Register("PluginInfos",
			typeof(ICollection<IPluginInfo>),
			typeof(PluginsView));

		[CreateNew]
		public PluginsPresenter Presenter
		{
			get
			{
				return GetValue(PresenterProperty) as PluginsPresenter;
			}
			set
			{
				SetValue(PresenterProperty, value);
			}
		}

		public ICollection<IPluginInfo> PluginInfos
		{
			get
			{
				return GetValue(PluginInfosProperty) as ICollection<IPluginInfo>;
			}
			set
			{
				SetValue(PluginInfosProperty, value);
			}
		}

		public new event EventHandler<EventArgs> Loaded;

		public event EventHandler<EventArgs> Close;

		public PluginsView()
		{
			InitializeComponent();

			//translate from WPF Loaded event to generic one
			base.Loaded += delegate
			{
				EventHelper.Raise(Loaded, this, EventArgs.Empty);
			};
		}

		private void _implicitlyTrustedPlugins_Filter(object sender, FilterEventArgs e)
		{
			Debug.Assert(e.Item is IPluginInfo);
			IPluginInfo pluginInfo = e.Item as IPluginInfo;
			e.Accepted = pluginInfo.IsImplicitlyTrusted;
		}

		private void _nonImplicitlyTrustedPlugins_Filter(object sender, FilterEventArgs e)
		{
			Debug.Assert(e.Item is IPluginInfo);
			IPluginInfo pluginInfo = e.Item as IPluginInfo;
			e.Accepted = !pluginInfo.IsImplicitlyTrusted;
		}

		//we save no extra data - it's all stored by the module white-list service
		object IOptionsPane.Data
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		object IOptionsPane.CreateData()
		{
			return null;
		}

		void IOptionsPane.Closed(bool applied)
		{
			if (applied)
			{
				Presenter.ApplyChanges();
			}
		}

		private static void Presenter_Changed(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
		{
			Debug.Assert(dependencyObject is PluginsView);

			if (e.NewValue != null)
			{
				Debug.Assert(e.NewValue is PluginsPresenter);
				(e.NewValue as PluginsPresenter).View = dependencyObject as PluginsView;
			}
		}
	}
}
